#!/usr/bin/env python3
"""
MCP服务器主程序
负责构建和管理MCP服务器
"""

import os
import sys
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from mcp_server.server_builder import MCPServerBuilder
from mcp_server.server_manager import MCPServerManager

# FastAPI应用
app = FastAPI(
    title="MCP Server Manager",
    description="MCP服务器管理服务",
    version="2.0.0"
)

@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {"status": "healthy", "service": "MCP Server Manager", "version": "2.0.0"}

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 路径配置
SERVER_DIR = Path(__file__).parent
# 使用共享目录 - 计算到项目根目录
workspace_root = Path(__file__).parent.parent.parent.parent  # 到达 xjc_MCP_GEN 根目录
SHARED_DIR = workspace_root / "shared"
GENERATED_DIR = SHARED_DIR / "generated"
FUNCTIONS_DIR = GENERATED_DIR / "functions"
SERVER_SCRIPT_PATH = GENERATED_DIR / "mcp_server.py"
TEMPLATE_PATH = workspace_root / "services" / "mcp-generator" / "mcp_generator" / "templates" / "mcp_server.py.j2"
FUNCTION_REGISTRY_PATH = GENERATED_DIR / "function_registry.json"

# 确保目录存在
GENERATED_DIR.mkdir(exist_ok=True)
FUNCTIONS_DIR.mkdir(exist_ok=True)

# 初始化组件
mcp_server_builder = MCPServerBuilder(
    template_path=str(TEMPLATE_PATH),
    output_path=str(SERVER_SCRIPT_PATH),
    registry_path=str(FUNCTION_REGISTRY_PATH),
    functions_dir=str(FUNCTIONS_DIR)
)

mcp_server_manager = MCPServerManager(
    main_script_path=str(SERVER_SCRIPT_PATH),
    watch_directory=str(GENERATED_DIR)
)

def force_reload_functions():
    """强制重新加载函数注册表"""
    try:
        # 重新加载函数注册表
        mcp_server_builder.function_manager.functions = mcp_server_builder.function_manager._load_registry()
        function_count = len(mcp_server_builder.function_manager.functions)
        print(f"✅ 已重新加载 {function_count} 个函数")
        return True, function_count
    except Exception as e:
        print(f"❌ 重新加载函数失败: {e}")
        return False, 0


@app.get("/server-status")
def get_server_status():
    """获取服务器状态"""
    return mcp_server_manager.get_server_status()


@app.post("/start-server") 
def start_server():
    """启动MCP服务器"""
    if not mcp_server_manager.is_running():
        # 如果服务器脚本不存在，先构建
        if not SERVER_SCRIPT_PATH.exists():
            print("Server script not found, building...")
            success = mcp_server_builder.build_server_script()
            if not success:
                return JSONResponse(
                    content={"message": "Failed to build server script"},
                    status_code=500
                )
        
        success = mcp_server_manager.start_with_validation()
        if success:
            return {"message": "MCP server started successfully"}
        else:
            return JSONResponse(
                content={"message": "MCP server started but failed health check"},
                status_code=500
            )
    return {"message": "MCP server is already running"}


@app.post("/stop-server")
def stop_server():
    """停止MCP服务器"""
    if mcp_server_manager.is_running():
        mcp_server_manager.stop()
        return {"message": "MCP server stopped"}
    return {"message": "MCP server is not running"}


@app.post("/restart-server")
def restart_server():
    """重启MCP服务器"""
    mcp_server_manager.restart()
    return {"message": "MCP server restarted"}


@app.post("/force-reload-functions")
def force_reload_functions_api():
    """强制重新加载函数注册表（API接口）"""
    try:
        success, function_count = force_reload_functions()
        if success:
            return {"message": f"已重新加载 {function_count} 个函数", "count": function_count}
        else:
            return JSONResponse(
                content={"message": "重新加载函数失败"},
                status_code=500
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"重新加载函数失败: {str(e)}")


@app.post("/rebuild-server")
def rebuild_server():
    """重建MCP服务器脚本"""
    try:
        success = mcp_server_builder.build_server_script()
        if success:
            return {"message": "Server script rebuilt successfully"}
        else:
            return JSONResponse(
                content={"message": "Failed to rebuild server script"},
                status_code=500
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/rollback-server")
def rollback_server():
    """回退到备份版本"""
    try:
        result = mcp_server_manager.rollback_to_backup()
        if result["success"]:
            return {"message": result["message"]}
        else:
            return JSONResponse(
                content={"message": result["message"]},
                status_code=400
            )
    except Exception as e:
        return JSONResponse(
            content={"message": f"回退操作失败: {str(e)}"},
            status_code=500
        )

@app.post("/rollback")
def rollback():
    """回退到备份版本（前端兼容接口）"""
    return rollback_server()


class RemoveFunctionRequest(BaseModel):
    function_name: str

@app.delete("/functions")
async def remove_function(request: RemoveFunctionRequest):
    """删除单个函数"""
    function_name = request.function_name
    try:
        # 检查函数是否存在
        function_info = mcp_server_builder.get_function_info(function_name)
        if not function_info:
            raise HTTPException(status_code=404, detail=f"函数 '{function_name}' 不存在")
        
        # 1. 删除MCP Server中的函数
        success = mcp_server_builder.remove_function(function_name)
        if not success:
            raise HTTPException(status_code=500, detail=f"删除函数 '{function_name}' 失败")
        
        # 2. 同步删除MCP Generator中的函数
        generator_delete_success = False
        try:
            import requests
            response = requests.delete("http://localhost:8010/functions", 
                                     json={"function_name": function_name}, timeout=15)
            if response.status_code == 200:
                generator_delete_success = True
                print(f"✅ 已从MCP Generator中删除函数 '{function_name}'")
            else:
                print(f"❌ 从MCP Generator删除函数失败，状态码: {response.status_code}")
        except Exception as e:
            print(f"❌ 从MCP Generator删除函数失败: {e}")
        
        # 3. 重建服务器脚本
        build_success = mcp_server_builder.build_server_script()
        if not build_success:
            return JSONResponse(
                content={"message": f"函数 '{function_name}' 删除成功，但重建服务器脚本失败"},
                status_code=207  # Partial success
            )
        
        # 4. 同步删除知识库中的向量嵌入
        kb_delete_success = False
        try:
            import requests
            response = requests.post("http://localhost:8080/api/rag/remove-function", 
                                   json={"function_name": function_name}, timeout=15)
            if response.status_code == 200:
                kb_delete_success = True
                print(f"✅ 已从知识库中删除函数 '{function_name}' 的向量嵌入")
            else:
                print(f"❌ 删除知识库向量嵌入失败，状态码: {response.status_code}")
        except Exception as e:
            print(f"❌ 删除知识库向量嵌入失败: {e}")
        
        # 5. 强制重新加载函数注册表（避免需要重启整个服务）
        force_reload_success, _ = force_reload_functions()
        print(f"✅ 已自动重新加载函数注册表，无需重启服务器")
        
        # 返回详细的删除结果
        success_parts = []
        warning_parts = []
        
        success_parts.append("MCP Server")
        if generator_delete_success:
            success_parts.append("MCP Generator")
        else:
            warning_parts.append("MCP Generator同步失败")
            
        if kb_delete_success:
            success_parts.append("RAG知识库")
        else:
            warning_parts.append("RAG知识库同步失败")
        
        message = f"函数 '{function_name}' 已从 {', '.join(success_parts)} 中删除，已自动重新加载"
        
        if warning_parts:
            message += f"，但 {', '.join(warning_parts)}"
            return JSONResponse(
                content={"message": message},
                status_code=207  # Partial success
            )
        else:
            return {"message": message}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除函数失败: {str(e)}")


@app.delete("/clear-functions")
async def clear_functions():
    """清空所有函数"""
    try:
        import shutil
        import json
        
        # 清空函数目录
        if FUNCTIONS_DIR.exists():
            shutil.rmtree(FUNCTIONS_DIR)
            FUNCTIONS_DIR.mkdir(exist_ok=True)
        
        # 重置函数注册表
        empty_registry = {
            "functions": {},
            "metadata": {
                "count": 0,
                "last_updated": None
            }
        }
        
        with open(FUNCTION_REGISTRY_PATH, 'w', encoding='utf-8') as f:
            json.dump(empty_registry, f, ensure_ascii=False, indent=2)
        
        # 同步清空MCP Generator中的函数
        generator_clear_success = False
        try:
            import requests
            response = requests.delete("http://localhost:8010/clear-functions", timeout=15)
            if response.status_code == 200:
                generator_clear_success = True
                print("✅ 已清空MCP Generator中的所有函数")
            else:
                print(f"❌ 清空MCP Generator失败，状态码: {response.status_code}")
        except Exception as e:
            print(f"❌ 清空MCP Generator失败: {e}")
        
        # 同步清空知识库（使用专门的清空接口）
        kb_clear_success = False
        try:
            import requests
            response = requests.post("http://localhost:8080/api/rag/clear", timeout=15)
            if response.status_code == 200:
                kb_clear_success = True
                print("✅ 已清空知识库中的所有向量嵌入")
            else:
                print(f"❌ 清空知识库失败，状态码: {response.status_code}")
        except Exception as e:
            print(f"❌ 清空知识库失败: {e}")
        
        # 重建服务器脚本
        success = mcp_server_builder.build_server_script()
        if not success:
            return JSONResponse(
                content={"message": "清空函数成功，但重建服务器脚本失败"},
                status_code=207  # Partial success
            )
        
        # 强制重新加载函数注册表（避免需要重启整个服务）
        force_reload_success, _ = force_reload_functions()
        print(f"✅ 已自动重新加载函数注册表，无需重启服务器")
        
        # 返回详细的清空结果
        success_parts = ["MCP Server"]
        warning_parts = []
        
        if generator_clear_success:
            success_parts.append("MCP Generator")
        else:
            warning_parts.append("MCP Generator同步失败")
            
        if kb_clear_success:
            success_parts.append("RAG知识库")
        else:
            warning_parts.append("RAG知识库同步失败")
        
        message = f"所有函数已从 {', '.join(success_parts)} 中清空，已自动重新加载"
        
        if warning_parts:
            message += f"，但 {', '.join(warning_parts)}"
            return JSONResponse(
                content={"message": message},
                status_code=207  # Partial success
            )
        else:
            return {"message": message}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"清空函数失败: {str(e)}")


@app.post("/validate-server")
def validate_server():
    """验证服务器健康状态"""
    status = mcp_server_manager.get_server_status()
    if status["is_running"] and status["is_healthy"]:
        return {"message": "Server is running and healthy", "status": status}
    elif status["is_running"] and not status["is_healthy"]:
        return JSONResponse(
            content={"message": "Server is running but unhealthy", "status": status},
            status_code=500
        )
    else:
        return JSONResponse(
            content={"message": "Server is not running", "status": status},
            status_code=500
        )


@app.get("/functions-info")
async def get_functions_info():
    """获取函数信息概览"""
    try:
        function_info = mcp_server_builder.get_function_info()
        return JSONResponse(content=function_info, status_code=200)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))




if __name__ == "__main__":
    import uvicorn
    print("🚀 Starting MCP Server Manager...")
    print(f"Generated directory: {GENERATED_DIR}")
    print(f"Server script path: {SERVER_SCRIPT_PATH}")
    print(f"Template path: {TEMPLATE_PATH}")
    
    # 强制重新加载函数注册表
    print("Loading function registry...")
    mcp_server_builder.function_manager.functions = mcp_server_builder.function_manager._load_registry()
    function_count = len(mcp_server_builder.function_manager.functions)
    print(f"Loaded {function_count} functions from registry")
    
    # 如果服务器脚本不存在，构建它
    if not SERVER_SCRIPT_PATH.exists():
        print("Building initial server script...")
        mcp_server_builder.build_server_script()
    
    # 启动MCP服务器
    print("Starting MCP server...")
    mcp_server_manager.start_with_validation()
    
    # 启动管理服务器
    uvicorn.run(app, host="0.0.0.0", port=8011)
